package com.tj.controller;

import com.aliyuncs.utils.StringUtils;
import com.tj.pojo.User;
import com.tj.service.UserService;
import com.tj.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    private Result<String> sendMsg(@RequestBody User user, HttpSession session) {

        //1.获取手机号
        String phone=user.getPhone();

        if(!StringUtils.isEmpty(phone)){
            //2.生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //3.阿里云短息服务发送短息
            //SMSUtils.sendMessage("tjwdssg","SMS_460700325",phone,code);
            //4.保存session
            session.setAttribute(phone,code);

            return Result.success("手机验证码发送成功");
        }
        return Result.error("手机验证码发送失败");
    }

    @PostMapping("/login")
    private Result<String> login(@RequestBody Map<String,String> map, HttpSession session, HttpServletRequest request) {

        //1.获取手机号,验证码（code）
        String phone=map.get("phone");
        String code=map.get("code");

        //2.获取code
        String Code=(String) session.getAttribute(phone);

        //3.判断验证码是否正确
        if(Code!=null&&Code.equals(code)) {
            //登录成功，将phone存入session
            request.getSession().setAttribute("user",phone);
            return Result.success("登录成功");
        }
        return Result.error("验证码错误");
    }
}
